package com.study.crypto.basic.pdf.container;

import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.IExternalSignatureContainer;
import com.study.crypto.basic.signer.exception.MyRuntimeException;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

/**
 * 计算 pdf 文件摘要值
 * @author Songjin
 * @since 2022-04-03 23:25
 */
public class DigestBlankContainer implements IExternalSignatureContainer {
    
    private final PdfName filter;
    private final PdfName subFilter;
    
    /** pdf文件摘要 */
    private byte[] digest;
    /** 摘要算法名称: SHA-1、SHA-256、SM3等 */
    private String digestAlgorithm;
    
    public DigestBlankContainer(PdfName filter, PdfName subFilter, String digestAlgorithm) {
        this.filter = filter;
        this.subFilter = subFilter;
        // 默认使用 sha256摘要算法
        this.digestAlgorithm = DigestAlgorithms.SHA256;
        if (StringUtils.isNotBlank(digestAlgorithm)) {
            this.digestAlgorithm = digestAlgorithm;
        }
    }
    
    byte[] calculateDigest(InputStream input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm, "BC");
            return DigestAlgorithms.digest(input, messageDigest);
        } catch (GeneralSecurityException | IOException e) {
            throw new MyRuntimeException("计算摘要异常", e);
        }
    }
    
    public byte[] getDigest() {
        return digest;
    }
    
    public byte[] sign(InputStream input) {
        digest = this.calculateDigest(input);
        return new byte[0];
    }
    
    public void modifySigningDictionary(PdfDictionary signDic) {
        signDic.put(PdfName.Filter, filter);
        signDic.put(PdfName.SubFilter, subFilter);
    }
}